package com.sui.bigdata.flink.sql.side.kudu.async;

import com.sui.bigdata.flink.sql.core.side.FieldInfo;
import com.sui.bigdata.flink.sql.core.side.JoinInfo;
import com.sui.bigdata.flink.sql.core.side.SideInfo;
import com.sui.bigdata.flink.sql.core.side.SideTableInfo;
import com.sui.bigdata.flink.sql.side.kudu.table.KuduSideTableInfo;
import org.apache.calcite.sql.SqlBasicCall;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlNode;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.shaded.guava18.com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;

public class KuduAsyncSideInfo extends SideInfo {


    public KuduAsyncSideInfo(RowTypeInfo rowTypeInfo, JoinInfo joinInfo, List<FieldInfo> outFieldInfoList, SideTableInfo sideTableInfo) {
        super(rowTypeInfo, joinInfo, outFieldInfoList, sideTableInfo);
    }

    @Override
    public void buildEqualInfo(JoinInfo joinInfo, SideTableInfo sideTableInfo, Map<Integer,String> sideFieldNameIndex, Map<Integer,String> inFieldNameIndex) {
        KuduSideTableInfo kuduSideTableInfo = (KuduSideTableInfo) sideTableInfo;

        String sideTableName = joinInfo.getSideTableName();

        SqlNode conditionNode = joinInfo.getCondition();

        List<SqlNode> sqlNodeList = Lists.newArrayList();
        if (conditionNode.getKind() == SqlKind.AND) {
            SqlNode leftConditionNode = conditionNode;
            SqlNode rightConditionNode = null;
            do {
                rightConditionNode = ((SqlBasicCall) leftConditionNode).getOperands()[1];
                leftConditionNode = ((SqlBasicCall) leftConditionNode).getOperands()[0];
                sqlNodeList.add(rightConditionNode);
            } while (leftConditionNode.getKind() != SqlKind.EQUALS);
            sqlNodeList.add(leftConditionNode);
        } else {
            sqlNodeList.add(conditionNode);
        }

        for(SqlNode sqlNode : sqlNodeList){
            dealEqualCon(sqlNode, sideTableName,sideFieldNameIndex,inFieldNameIndex);
        }
        sqlCondition = "select ${selectField} from ${tableName} where ";

        for (int i = 0; i < joinCondition.size(); i++) {
            String oneCondition = joinCondition.get(i);
            sqlCondition +=   oneCondition + " and ";
        }

        for (int i = 0; i < equalFieldList.size(); i++) {
            String equalField = equalFieldList.get(i);

            sqlCondition += equalField + "=? ";
            if (i != equalFieldList.size() - 1) {
                sqlCondition += " and ";
            }
        }


        sqlCondition = sqlCondition.replace("${tableName}", kuduSideTableInfo.getTableName()).replace("${selectField}", sideSelectFields);
        System.out.println("---------side_exe_sql-----\n" + sqlCondition);
    }

}
